﻿using System;
using System.Linq;
using Expect.Core.Fixtures;

namespace Expect.Report.Word.Processors
{
    public class ImageDescriptionFixtureProcessor : DefaultProcessor, IProcessor<ImageDescriptionFixture>
    {
        private string[] _assemblyRessources;

        public Func<string, string> ResolveStyle { get; set; }
        
        public override void Apply()
        {
            if (_assemblyRessources == null)
            {
                _assemblyRessources = TargetAssembly.GetManifestResourceNames();
            }
            AddImage(Fixture.Rows[0].AsText());
        }

        private void AddImage(string imageResourceName)
        {
            var targetName = imageResourceName.Replace("\\", ".");
            targetName = targetName.Replace("/", ".");
            var resname = _assemblyRessources.FirstOrDefault(r => string.Compare(r, targetName, true) == 0);

            if (resname == null)
            {
                resname = _assemblyRessources.FirstOrDefault(r => r.EndsWith(targetName, StringComparison.OrdinalIgnoreCase));
            }

            if (resname != null)
            {
                using (var stream = TargetAssembly.GetManifestResourceStream(resname))
                {
                    Document.MainDocumentPart.AddImage(null, stream);
                }
            }
            else
            {
                Console.WriteLine("Image not found : " + imageResourceName);
            }
        }
    }
}
